package com.gxkj.drm.controllers;


import com.gxkj.drm.constant.WebConstant;
import com.gxkj.drm.dto.CodeMsg;
import com.gxkj.drm.entitys.PushUser;
import com.gxkj.drm.entitys.PushUserOperateLog;
import com.gxkj.drm.enums.RoleType;

import com.gxkj.drm.service.ResourceManageService;
import com.gxkj.drm.service.UserService;
import com.gxkj.drm.util.MD5;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
 * Created by changxiangyang on 2017/9/19.
 */
@Controller
public class UserController extends BaseController{

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource
    private UserService userService;

    @Resource
    private ResourceManageService resourceManageService;

    /**
     * 用户列表
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @RequestMapping(value = "/user/userList")
    public String userList(final HttpServletRequest request, Model model) {
        PushUser user = this.getUser(request);
        List<PushUser> users = userService.getAllUser(user.getLevel());

        model.addAttribute("users", users);
        model.addAttribute("url", WebConstant.URL_USER_LIST);
        return WebConstant.PAGE_HOME;
    }


    /**
     * 编辑用户信息
     *
     * @param model
     * @param name
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @RequestMapping(value = WebConstant.PATH_EDIT_USER)
    public String editUser(final HttpServletRequest request, Model model, String name) {
        PushUser user = this.getUser(request);
        PushUser editUser = userService.getUserByName(name);
        String[] clusterArray = StringUtils.split(editUser.getClusters(), ",");
        List<String> userClusters;
        if (clusterArray == null) {
            userClusters = new ArrayList<>();
        } else {
            userClusters = Arrays.asList(clusterArray);
        }
        List<String> allClusters = resourceManageService.getClusterList();
        Map<String, String> clusters = new HashMap<>(allClusters.size());
        for (String c : allClusters) {
            clusters.put(c, userClusters.contains(c)?"1":"0");
        }

        model.addAttribute("level", user.getLevel());
        model.addAttribute("clusters", clusters);
        model.addAttribute("user", editUser);
        return WebConstant.PAGE_EDIT_USER;
    }

    /**
     * 保存编辑用户信息内容
     * @param updataUser
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_UPDATE_USER)
    public CodeMsg updateUser(PushUser updataUser) {
        try {
            // 被修改的用户名和ID必须一致
            PushUser dbUser = userService.getUserByName(updataUser.getName());
            if (dbUser.getId() != updataUser.getId()) {
                CodeMsg error = CodeMsg.ERROR;

                error.setMsg("非法修改");
                return error;
            }
            // 清除密码
            updataUser.setPwd(null);
            // 更新用户信息
            int num = userService.updateUser(updataUser);
            return num>0 ? CodeMsg.SUCCESS : CodeMsg.ERROR;
        } catch (Exception e) {
            LOGGER.error("修改用户信息异常:{}", e);
            CodeMsg error = CodeMsg.ERROR;
            error.setMsg("服务器异常");
            return error;

        }
    }


    /**
     * 修改密码页面
     * @param request
     * @param model
     * @param name
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @RequestMapping(value = WebConstant.PAGE_CHANGE_PASSWORD)
    public String changPassword(final HttpServletRequest request, Model model, String name) {
        model.addAttribute("name", name);
        return WebConstant.PAGE_CHANGE_PASSWORD;
    }


    /**
     * 修改密码
     * @param name
     * @param password
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_CHANGE_PASSWORD)
    public CodeMsg changePwd(String name, String password) {
        try {
            PushUser user = userService.getUserByName(name);
            if (user != null) {
                user.setPwd(MD5.md5(password));
                int c = userService.updateUser(user);
                if (c > 0) {
                    return CodeMsg.SUCCESS;
                }
            } else {
                LOGGER.info("修改密码-不存在用户名:{}.", name);
            }

            return CodeMsg.ERROR;
        } catch (Exception e) {
            LOGGER.error("修改密码异常:{}", e);
            return CodeMsg.ERROR;
        }
    }

    /**
     * 删除用户
     * @param name
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_DELETE_USER)
    public CodeMsg deleteUser(String name) {
        int c = userService.deleteUserByName(name);
        return c > 0 ? CodeMsg.SUCCESS : CodeMsg.ERROR;
    }

    /**
     * 增加用户界面
     * @param request
     * @param model
     * @return
     */
//    @Permission(role = RoleType.ADMIN)
    @RequestMapping(value = WebConstant.PAGE_ADD_USER)
    public String addUser(final HttpServletRequest request, Model model) {
        PushUser user = getUser(request);
        List<String> clusterList = resourceManageService.getClusterList();
        model.addAttribute("level", user.getLevel());
        model.addAttribute("clusters", clusterList);
        return WebConstant.PAGE_ADD_USER;
    }


    /**
     * 新增用户名信息
     * @param user
     * @return
     */
//    @Permission(needLogin = false, role = RoleType.ADMIN)
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_ADD_USER)
    public CodeMsg inserUser(PushUser user) {
        String pwd = user.getPwd();
        user.setPwd(MD5.md5(pwd));
        int c = userService.addUser(user);
        return c > 0 ? CodeMsg.SUCCESS : CodeMsg.ERROR;
    }


    /**
     * 检测用户名是否存在
     * @param name
     * @return
     */
//    @Permission(needLogin = false, role = RoleType.USER)
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_CHECK_NAME)
    public CodeMsg checkName(String name) {
        PushUser user = userService.getUserByName(name);
        return user==null?CodeMsg.SUCCESS:CodeMsg.ERROR;
    }

    /**
     * 用户操作记录
     * @return
     */
    @RequestMapping(value = WebConstant.PAGE_USER_RECORD)
    public String userReCord(final HttpServletRequest request, Model model) {
        List<PushUserOperateLog> pushUserOperateLogList = userService.getUserOperateLogList(getUser(request));
        model.addAttribute("url", WebConstant.URL_USER_RECORD);
        model.addAttribute("userOperateLogList", pushUserOperateLogList);
        return WebConstant.PAGE_HOME;
    }

    /**
     * 查看用户信息
     * @param request
     * @param model
     * @return
     */
    @RequestMapping(value = WebConstant.PATH_USER_INFO)
    public String userInfo(final HttpServletRequest request, Model model) {
        PushUser user = getUser(request);
        String levelName = RoleType.find(user.getLevel()).getName();
        user.setLevelName(levelName);
//        String[] clusterArray = StringUtils.split(user.getClusters(), ",");
//        List<String> clusters = null;
//        if (clusterArray != null) {
//            clusters = Arrays.asList(clusterArray);
//        }
//        model.addAttribute("clusters", clusters);

        model.addAttribute("user", user);
        return WebConstant.PAGE_USER_INFO;
    }

    /**
     * 更新用户信息
     * @param request
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = WebConstant.PATH_USER_INFO_UPDATE)
    public CodeMsg updateUserInfo(final HttpServletRequest request, PushUser user) {
        try {
            PushUser operator = getUser(request);
            if (operator != null && user != null) {
                if (operator.getName().equals(user.getName())
                        && (operator.getLevel() == user.getLevel())) {
                    user.setId(operator.getId());
                    if (StringUtils.isNotBlank(user.getPwd())) {
                        user.setPwd(MD5.md5(user.getPwd()));
                    }
                    // 禁止修改授权集群
                    user.setClusters(null);
                    int num = userService.updateUser(user);
                    logger.info("更新用户信息成功, 参数:{}", user);
                    return num>0 ? CodeMsg.SUCCESS : CodeMsg.ERROR;
                }
            }
            logger.info("更新用户信息失败, 参数:{}", user);
            return CodeMsg.ERROR;
        } catch (Exception e) {
            logger.error("更新用户信息异常:", e);
            return CodeMsg.ERROR;
        }
    }
}
